<?php
namespace App\DataBase;


class ModelSet implements \Iterator, \JsonSerializable, \Countable
{
    /**
     * @var array 原始数据，从数据库查询出来的数据
     */
    private $_rawData = [];
    private $_position = 0;
    /**
     * @var string 对应的需要实例化的Model
     */
    private $_modelClassName;
    /**
     * @var string 分表参数
     */
    private $_splitSuffix;

    use JsonSerializableTrait, CountableTrait;

    /**
     * ModelSet constructor.
     * @param string $modelClassName
     * @param array $_rawData
     * @param string $splitSuffix
     */
    public function __construct($modelClassName, array $_rawData, $splitSuffix = '')
    {
        $this->_rawData = $_rawData;
        $this->_modelClassName = $modelClassName;
        $this->_splitSuffix = $splitSuffix;
    }

    public function rewind()
    {
        $this->_position = 0;
    }

    public function current()
    {
        if (!isset($this->_rawData[$this->_position])) {
            return null;
        }
        /**
         * @var Model $model
         */
        $model = new $this->_modelClassName($this->_splitSuffix);
        $model->initRawData($this->_rawData[$this->_position]);
        return $model;
    }

    public function key()
    {
        return $this->_position;
    }

    public function next()
    {
        ++$this->_position;
    }

    public function valid()
    {
        return isset($this->_rawData[$this->_position]);
    }
}